package de.uhilger.netzpult.server;

import java.io.IOException;
import java.io.Writer;
import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.ConsoleHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import de.uhilger.netzpult.server.db.DataStorage;
import de.uhilger.netzpult.server.db.DataStorageImpl;
import de.uhilger.netzpult.shared.Document;

public class FindServlet extends HttpServlet {

	private static final long serialVersionUID = 4049447390425851726L;

	protected DataStorage ds;
	protected String mode;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			goFind(req, resp);
	}

		@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			goFind(req, resp);
	}

		private void goFind(HttpServletRequest req, HttpServletResponse resp) {
			String searchItem = req.getParameter("item");
			if(searchItem != null && searchItem.length() > 0) {
				try {
					List<Document> documents = ds.findDocuments(getUserName(req), searchItem);
					Writer w = resp.getWriter();
					String title = "netzpult Suchergebnis";
					String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
					DocumentServer.header(w, title, date, -1);
					w.write("<body>");
					w.write("<div id=\"Seite\">");
					w.write("<h3>Suchergebnis</h3>");
					Iterator<Document> i = documents.iterator();
					while(i.hasNext()) {
						Document document = i.next();
						w.write("<p>");
						w.write("<a href=\"dok/");
						w.write(Integer.toString(document.getId()));
						w.write("\">");
						w.write(document.getTitle());
						w.write("</a>");
						w.write("</p>");
					}
					w.write("</div>");
					w.write("<p id=\"copyrightFooter\">");
					w.write(DocumentServer.getCopyrightFooter());
					w.write("</p>");
					w.write("</body>");
					w.write("</html>");
					w.flush();
				} catch (Exception e) {
					DocumentServer.logError(e);
				}
			} else {
				Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).finest("searchItem='" + searchItem + "'");
			}
		}
		
	private String getUserName(HttpServletRequest req) {
		String userName = null;
		Principal p = req.getUserPrincipal();
		if(p != null) {
			userName = p.getName();
		}
		if(userName == null) {
			userName = AbstractWebfilesServlet.ANONYMOUS_OWNER;
		}
		Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).finest(userName);
		return userName;
	}

	public void init(ServletConfig config) throws ServletException {
		
		ServletContext context = config.getServletContext();

		mode = context.getInitParameter(AbstractWebfilesServlet.MODE);
		String dbtype = context.getInitParameter(AbstractWebfilesServlet.DB_TYPE);
		String dburl = context.getInitParameter(AbstractWebfilesServlet.DB_URL);
		
		Level loglevel = Level.FINEST;
		if(config != null) {
			String logLevelStr = context.getInitParameter(AbstractWebfilesServlet.LOGLEVEL);
			if(logLevelStr != null) {
				loglevel = Level.parse(logLevelStr.toUpperCase());
			}
		}
		
		Object o = context.getAttribute(DataStorage.NAME);
		if (o == null) {
			//System.out.println(new Date() + " UploadServlet.init creating DatabaseAdapter");
			ds = new DataStorageImpl(mode, dbtype, dburl);
			context.setAttribute(DataStorage.NAME, ds);
		} else {
			ds = (DataStorage) o;
		}
		Logger globalLogger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
		Handler[] handlers = globalLogger.getHandlers();
		if(handlers.length == 0) {
			Handler handler = new ConsoleHandler();
			handler.setLevel(loglevel);
			globalLogger.addHandler(handler);
			globalLogger.setLevel(loglevel);
		}
		super.init(config);
	}
}
